
import { _decorator, Component, sys, AudioClip, AudioSource } from 'cc';
import { SDKManager } from './SDKManager';
const { ccclass, property } = _decorator;

interface audioData {
    isMusic: boolean,
    isSound: boolean,
    isShock: boolean
}
@ccclass('AudioManager')
export class AudioManager extends Component {
    @property(AudioClip)
    public bg: AudioClip = null!;

    @property(AudioClip)
    public click: AudioClip = null!;

    @property(AudioClip)
    public eliminate: AudioClip = null!;

    @property(AudioClip)
    public win: AudioClip = null!;
    @property(AudioClip)
    public over: AudioClip = null!;

    public audioComp: AudioSource = null!;

    @property({
        displayName: '音乐开关'
    })
    public isMusic: boolean = true;

    @property({
        displayName: '音效开关'
    })
    public isSound: boolean = true;

    @property({
        displayName: '震动开关'
    })
    public isShock: boolean = true;

    public getIsMusic(): boolean {
        return this.isMusic;
    }

    public getIsSound(): boolean {
        return this.isSound;
    }

    public getIsShock(): boolean {
        return this.isShock;
    }

    public setIsMusic(is: boolean): void {
        this.isMusic = is;
        this.playMusic();
        this.saveAudioData();
    }

    public setIsSound(is: boolean): void {
        this.isSound = is;
        this.saveAudioData();
    }

    public setIsShock(is: boolean): void {
        this.isShock = is;
        this.saveAudioData();
    }

    start() {
        this.loadAudioData();
        this.audioComp = this.getComponent(AudioSource)!;
        this.playMusic();
    }

    loadAudioData() {
        let jsonStr = sys.localStorage.getItem('AUDIO_DATA');

        let josnData = jsonStr ? JSON.parse(jsonStr) as audioData : { isMusic: true, isSound: true, isShock: true };
        this.isMusic = josnData.isMusic;
        this.isSound = josnData.isSound;
        this.isShock = josnData.isShock;
    }

    saveAudioData() {
        let josnData = { isMusic: this.isMusic, isSound: this.isSound, isShock: this.isShock };
        let jsonStr = JSON.stringify(josnData);
        sys.localStorage.setItem('AUDIO_DATA', jsonStr);
    }

    playMusic() {
        if (!this.isMusic) {
            this.audioComp.stop();
            return;
        }
        this.audioComp.clip = this.bg;
        this.audioComp.loop = true;
        this.audioComp.volume = 0.5;
        this.audioComp.play();
    }


    playSound(str = 'click') {
        if (this.isSound) {
            this.audioComp.playOneShot(this[`${str}`]);
        }
        if (this.isShock) SDKManager.vibrateShort();
    }

}
